/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eit.ntc.lmsbackend.remote.xml;

import com.eit.toschoolonline.lms.jdo.LearningItemM;
import com.eit.toschoolonline.lms.service.LearningItemService;
import com.eit.toschoolonline.lms.service.exception.LearningItemServiceException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author oxopro
 */
public class MyItemAction extends DownloadAction {

    private LearningItemService learningItemService;
    private int numItem;
    private String patternDate;

    public int getNumItem() {
        return numItem;
    }

    public void setNumItem(int numItem) {
        this.numItem = numItem;
    }

    public String getPatternDate() {
        return patternDate;
    }

    public void setPatternDate(String patternDate) {
        this.patternDate = patternDate;
    }

    public LearningItemService getLearningItemService() {
        return learningItemService;
    }

    public void setLearningItemService(LearningItemService learningItemService) {
        this.learningItemService = learningItemService;
    }

    @Override
    protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getRemoteUser();
        List allItems = new ArrayList();
        allItems = learningItemService.getAllItems(username, getNumItem());

        String xml = createXML(allItems, getNumItem());
        return new XMLStreamInfo(xml);
    }

    private String createXML(List hotItems, int numItem) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document xmlDoc = db.newDocument();
            Element allItemElement = xmlDoc.createElement("AllItems");

            for (int i = 0; i < numItem; i++) {
                if (i < hotItems.size()) {
                    LearningItemM learningItem = (LearningItemM) hotItems.get(i);
                    Element itemElement = xmlDoc.createElement("Item");

                    Element idElement = xmlDoc.createElement("ItemId");
                    idElement.setTextContent(learningItem.getItemId() + "");

                    Element nameElement = xmlDoc.createElement("ItemName");
                    nameElement.setTextContent(learningItem.getItemName() + "");

                    Element codeElement = xmlDoc.createElement("ItemCode");
                    codeElement.setTextContent(learningItem.getItemCode() + "");

                    Element updateElement = xmlDoc.createElement("Update");
                    Date d = learningItem.getUpdateDate();
                    DateFormat df = new SimpleDateFormat(patternDate);
                    updateElement.setTextContent(df.format(d));

                    itemElement.appendChild(idElement);
                    itemElement.appendChild(nameElement);
                    itemElement.appendChild(codeElement);
                    itemElement.appendChild(updateElement);

                    allItemElement.appendChild(itemElement);
                } else {
                    Element itemElement = xmlDoc.createElement("Item");

                    Element idElement = xmlDoc.createElement("ItemId");
                    idElement.setTextContent("");

                    Element nameElement = xmlDoc.createElement("ItemName");
                    nameElement.setTextContent("");

                    Element codeElement = xmlDoc.createElement("ItemCode");
                    codeElement.setTextContent("");

                    Element updateElement = xmlDoc.createElement("Update");
                    Date d = new Date();
                    DateFormat df = new SimpleDateFormat(patternDate);
                    updateElement.setTextContent(df.format(d));

                    itemElement.appendChild(idElement);
                    itemElement.appendChild(nameElement);
                    itemElement.appendChild(codeElement);
                    itemElement.appendChild(updateElement);

                    allItemElement.appendChild(itemElement);
                }
            }
            xmlDoc.appendChild(allItemElement);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);

            DOMSource source = new DOMSource(xmlDoc);
            transformer.transform(source, result);
            return sw.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new LearningItemServiceException(ex.getMessage());
        }

    }

    protected class XMLStreamInfo implements StreamInfo {

        protected String contentXML;

        public XMLStreamInfo(String content) {
            contentXML = content;
        }

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(contentXML.getBytes("UTF-8"));
        }

        public String getContentType() {
            return new String("text/xml");
        }
    }
}
